import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';

import '../../api/pick/index.dart';
import '../../components/tabFilter/TabFilterItem.dart';
import '../../components/tabFilter/index.dart';

class PickSerach extends StatefulWidget {
  const PickSerach({
    super.key,
  });

  @override
  State<PickSerach> createState() => _PickSerachState();
}

class _PickSerachState extends State<PickSerach> {

  String _code = '';

  List<String> _pickStatus = [];

  List<dynamic> _list = [];

  ScrollController _controller = ScrollController();

  late double _maxPage;

  int _page = 1;

  int _size = 8;

  bool _statusFlag = false;

  List _statusFilters = [];

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getTabFilters();
      search();
    });
    _controller.addListener(listenerController);
  }

  void listenerController() {
    if (_controller.position.pixels == _controller.position.maxScrollExtent) {
      if (_page < _maxPage) {
        setState(() {
          _page++;
        });
        search();
      }
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void getTabFilters() {
    PickApi.of(context).getTabFilters().then((res) {
      setState(() {
      _statusFilters = res.data["data"];
      });
    });
  }


  // 设置值
  void setValue(String key, String value) {
    switch (key) {
      case 'code':
        setState(() => _code = value);
        break;
      default:
        throw Exception('key error');
    }
  }


  void clear() {
    setState(() {
      _pickStatus = [];
    });
  }

  searchByCode(code){
    _code = code;
    resetSearchList();
    search();
  }
  /// 查询
  void search() {
    PickApi.of(context)
        .pickByFilter(_code, _pickStatus,_size,_page)
        .then((res) {
      if (StringUtils.isNotNull(res.data)) {
        setState(() {
          _list.addAll(res.data['data']['rows']);
          _maxPage = res.data['data']['total'] / _size;
        });
        hideKeyBorder();
      }
    });
  }

  Color getStatusBgColor(String code) {
    switch (code) {
      case '0':
        return Colors.amber;
      case '10':
        return Colors.amber;
      case '20':
        return Colors.amber;
      case '30':
        return Colors.greenAccent;
      case '99':
        return Colors.grey;
      default:
        return Colors.white;
    }
  }

  void detail(index) {
    Navigator.pushNamed(context, "/pick-detail-search",
        arguments: _list[index]);
  }

  void go(String path) {
    Navigator.pushNamed(context, path);
  }

  void changeFilters(Map<String, String> filter) {
    resetSearchList();
    _statusFlag = false;
    for (String key in filter.keys) {
      switch (key) {
        case "_statusFilters":
          _statusFlag = true;
      }
    }
    setState(() {
      _pickStatus =
        _statusFlag ? filter['_statusFilters'].toString().split(',') :  [];
    });
    search();
  }

  void resetSearchList() {
    setState(() {
      _list = [];
      _page = 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '拣配单查询'),
      body: GestureDetector(
          onTap: hideKeyBorder,
          child: Column(
            children: [
              BrnSearchText(
                  autoFocus: false,
                  hintText: '拣配单/ERP单据',
                  onTextChange: (value){
                    setValue('code', value);
                  },
                  onTextCommit: searchByCode
              ),
              TabFilter(
                  item: [
                    TabFilterItem(
                        label: "状态",
                        columnKey: "_statusFilters",
                        child: _statusFilters,
                        listSize: 1,
                        type: "Checkbox"),
                  ],
                  onSelectionChanged: (
                      int menuIndex,
                      Map<String, String> filterParams,
                      Map<String, String> customParams,
                      BrnSetCustomSelectionMenuTitle setCustomTitleFunction,
                      ) {
                    changeFilters(filterParams);
                  }),
              Expanded(
                child: ListContainer(
                  controller: _controller,
                  actions: [
                    SlidActions(
                      onPressed: detail,
                      label: '明细',
                      backgroundColor: Colors.green,
                      icon: Icons.search,
                    )
                  ],
                  // title: '拣配单信息',
                  length: _list.length,
                  children: (index) {
                    return [
                      Horizontal(items: [
                        HorizontalItem(
                          label: '拣配单号：',
                          value: _list[index]['pickCode'],
                        )
                      ]),
                      Horizontal(items: [
                        HorizontalItem(
                            label: '状态：',
                            value: _list[index]['statusName'],
                            fontColor: Colors.white,
                            valueBackground: getStatusBgColor
                              (_list[index]['status'])
                        ),
                        HorizontalItem(
                          label: '拣配人：',
                          value: _list[index]['pickUser'],
                        ),
                      ]),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '优先级：',
                          value: _list[index]['priority'] != null ?
                          _list[index]['priority'].toString() : '',
                        ),
                        HorizontalItem(
                          label: '配送终点：',
                          value: _list[index]['deliveryEndStation'],
                        )
                      ]),
                    ];
                  },
                ),
              ),
            ],
          )),
    );
  }
}
